package com.example.lockfulldemo.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.lockfulldemo.entity.RolePermissionEntity;
import com.example.lockfulldemo.entity.UserInfoEntity;
import com.example.lockfulldemo.entity.UserRoleEntity;
import com.example.lockfulldemo.mapper.*;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author Think
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {
    @Resource
    private UserInfoMapper userInfoMapper;
    @Resource
    private UserRoleMapper userRoleMapper;
    @Resource
    private RoleMapper roleMapper;
    @Resource
    private RolePermissionMapper rolePermissionMapper;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        UserInfoEntity user = userInfoMapper.selectOne(new LambdaQueryWrapper<UserInfoEntity>().eq(UserInfoEntity::getLoginName, username));
        if(ObjectUtil.isEmpty(user)){
            return null;
        }
        List<UserRoleEntity> userRoleEntities = userRoleMapper.selectList(new LambdaQueryWrapper<UserRoleEntity>()
                .select(UserRoleEntity::getRoleCode)
                .eq(UserRoleEntity::getUserId, user.getUserId()));
        List<RolePermissionEntity> rolePermissionEntities = rolePermissionMapper.selectList(new LambdaQueryWrapper<RolePermissionEntity>()
                .select(RolePermissionEntity::getPermissionCode)
                .in(RolePermissionEntity::getRoleCode, userRoleEntities.stream().map(e -> e.getRoleCode()).collect(Collectors.toList())));
        List<String> collect = new ArrayList<>();
        for(RolePermissionEntity rolePermissionEntity : rolePermissionEntities){
            collect.add(rolePermissionEntity.getPermissionCode());
        }
        UserDetails userDetails = User.withUsername(user.getLoginName())
                .password(user.getPassword())
                .authorities((String[])collect.toArray(new String[collect.size()]))
                .build();
        return userDetails;
    }
}
